<template>
  <el-dialog
    v-model="visible"
    title="选择测试模板"
    width="80%"
    top="5vh"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <div class="template-select-container">
      <div class="search-bar">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入模板名称"
          clearable
          style="width: 200px; margin-right: 10px"
          @keyup.enter="handleSearch"
        />
        <el-button @click="handleSearch" type="primary">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <el-table
        :data="tableData"
        v-loading="loading"
        border
        style="width: 100%; margin-top: 16px"
        highlight-current-row
        @current-change="handleCurrentChange"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="模板名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="version" label="版本" width="100" align="center">
          <template #default="{ row }">
            <el-tag type="info" size="small">v{{ row.version || 1 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.remark || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.size"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSearch"
          @current-change="handleSearch"
        />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :disabled="!selectedTemplate">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { pageTestTemplates, type TestTemplate, type TestTemplateQuery } from '@/apis/template/testTemplate'

const emit = defineEmits(['confirm', 'cancel'])

const visible = ref(false)
const loading = ref(false)
const tableData = ref<TestTemplate[]>([])
const total = ref(0)
const selectedTemplate = ref<TestTemplate | null>(null)

const queryParams = reactive<TestTemplateQuery>({
  name: undefined,
  page: 1,
  size: 10
})

const open = async () => {
  visible.value = true
  selectedTemplate.value = null
  await fetchData()
}

const fetchData = async () => {
  try {
    loading.value = true
    const res = await pageTestTemplates(queryParams)
    if (res && res.data && res.data.data) {
      const pageData = res.data.data
      if (pageData.list && Array.isArray(pageData.list)) {
        tableData.value = pageData.list
        total.value = pageData.total || 0
      } else {
        tableData.value = []
        total.value = 0
      }
    } else {
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取测试模板列表失败:', error)
    ElMessage.error('获取测试模板列表失败')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  queryParams.page = 1
  fetchData()
}

const resetSearch = () => {
  queryParams.name = undefined
  queryParams.page = 1
  fetchData()
}

const handleCurrentChange = (currentRow: TestTemplate | null) => {
  selectedTemplate.value = currentRow
}

const handleConfirm = () => {
  if (!selectedTemplate.value) {
    ElMessage.warning('请选择一个测试模板')
    return
  }
  emit('confirm', selectedTemplate.value)
  visible.value = false
}

const handleCancel = () => {
  emit('cancel')
  visible.value = false
}

const formatTime = (time?: string) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

defineExpose({ open })
</script>

<style scoped lang="scss">
.template-select-container {
  padding: 10px;
  
  .search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    gap: 10px;
  }
  
  .pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table) {
  .el-table__header {
    th {
      background-color: #f5f7fa;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }
  
  .el-table__body {
    tr {
      &:hover {
        background-color: #f5f7fa;
        cursor: pointer;
      }
      
      &.current-row {
        background-color: var(--el-color-primary-light-9);
      }
    }
  }
}
</style>

